<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\validate\PowerValidate;
use Exception;
use think\facade\Db;
use think\facade\Log;
use think\Request;

/**
 * @note    权限
 * @author  liujian
 * Class Power
 * @package app\admin\controller
 * @Create  Date : 2021年04月01日 下午1:57:18
 */
class Power extends Base
{
    /**
     * @OA\Get(path="/power/list",
     *   tags={"权限管理"},
     *   summary="权限列表",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="status", in="query", description="状态 1正常 2冻结 0所有", @OA\Schema(type="int", default="0")),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *               @OA\Property(property="list", type="object",description="列表,具体值参考详情"),
     *          ),
     *      ),
     *   ),
     * )
     */
    public function list()
    {
        //
        $list = Db::name("power")
            ->order('sort','desc')
            ->select()->toArray();
        $list = recursion($list);
        return $this->jsonSuccessData("获取成功", $list);
    }

    /**
     * @OA\Post(path="/power/delete",
     *   tags={"权限管理"},
     *   summary="权限删除",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="ID", property="id", type="int", default=""),
     *           required={"id"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function delete($id)
    {
        /*if ($info['level'] == 1) {
            // 删除二级权限
            Db::name("power")->where('pid', $info['id'])->delete();
            $power_ids = Db::name("power")->where('pid', 'in', $id)->column("id");
            // 删除二级角色权限表
            Db::name("role_power")->where("power_id", 'in', $power_ids)->delete();

            // 删除三级权限
            $power_ids_child = Db::name("power")->where('pid', 'in', $power_ids)->column("id");
            Db::name("power")->where('pid', 'in', $power_ids_child)->delete();
            // 删除三级角色权限表
            Db::name("role_power")->where("power_id", 'in', $power_ids_child)->delete();
        } else if ($info['level'] == 2) {
            // 删除三级权限
            Db::name("power")->where('pid', $info['id'])->delete();
            $power_ids = Db::name("power")->where('pid', 'in', $id)->column("id");
            // 删除角色权限表
            Db::name("role_power")->where("power_id", 'in', $power_ids)->delete();
        }*/
        //
        $list = Db::name("power")->where('id', 'in', $id)->select()->toArray();
        $result= Db::name("power")->where('id', 'in', $id)->delete();
        if ($result) {
            // 删除权限表
            Db::name("role_power")->where("power_id", 'in', $id)->delete();
            addAdminLog("删除权限$id" . "权限：" . json_encode($list), '删除权限');
            return $this->jsonSuccessData("操作成功");
        } else {
            return $this->jsonFailData("操作失败");
        }
    }

    /**
     * 重新指定等级
     *
     * @param int $id
     * @return \think\Response
     */
    public function reserver()
    {
        $level_1 = Db::name("power")->where('pid', 0)->column('id');
        Db::name("power")->where('pid', 0)->update(['level' => 1]);

        $level_2 = Db::name("power")->where('pid', 'in', $level_1)->column('id');
        Db::name("power")->where('id', 'in', $level_2)->update(['level' => 2]);

        $level_3 = Db::name("power")->where('pid', 'in', $level_2)->column('id');

        Db::name("power")->where('id', 'in', $level_3)->update(['level' => 3]);

        $level_4 = Db::name("power")->where('pid', 'in', $level_3)->column('id');
        Db::name("power")->where('id', 'in', $level_4)->update(['level' => 4]);
    }

    /**
     * @OA\Post(path="/power/save",
     *   tags={"权限管理"},
     *   summary="权限添加/修改",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="权限ID", property="id", type="int", default=""),
     *           @OA\Property(description="节点标题", property="title", type="string", default=""),
     *           @OA\Property(description="节点名称", property="name", type="int", default=""),
     *           @OA\Property(description="1权限 2子权限", property="type", type="string", default=""),
     *           @OA\Property(description="节点图标", property="node_icon", type="int", default="1"),
     *           @OA\Property(description="状态 1正常 2冻结", property="status", type="int", default="1"),
     *           @OA\Property(description="路由", property="routing", type="int", default="1"),
     *           @OA\Property(description="排序", property="sort", type="int", default="1"),
     *           @OA\Property(description="父级ID", property="pid", type="int", default="1"),
     *           required={"title", "name", "type", "status", "sort"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function save(Request $request)
    {
        $id = input('id');
        //
        // 启动事务
        Db::startTrans();
        try {
            $update_data = array(
                'title'       => input("title"),
                'name'        => input("name"),
                'node_icon'   => input("node_icon"),
                'status'      => input("status"),
                'sort'        => input("sort"),
                'routing'     => input("routing"),
                'pid'         => input("pid"),
                'type'        => input("type"),
                'update_time' => date("Y-m-d H:i:s")
            );

            validate(PowerValidate::class)->check($update_data);

            if (input("pid") == 0) {
                $update_data['level'] = 1;
            } else {
                $power_pinfo = Db::name("power")->where('id', input("pid"))->find();
                if ($power_pinfo['level']) $update_data['level'] = $power_pinfo['level'] + 1;
                if ($update_data['level'] > 3) throw new Exception("等级不可以为4");
            }
            if ($id) {
                $result= Db::name("power")->where('id', $id)->update($update_data);
                if (!$result) throw new Exception("操作失败");

                addAdminLog("修改权限$id" . "信息为" . json_encode($update_data), '修改权限信息');
            } else {
                $update_data['create_time'] = date("Y-m-d H:i:s");
                //
                $result= Db::name("power")->insert($update_data);
                if (!$result) throw new Exception("操作失败");

                addAdminLog("添加权限" . "信息为" . json_encode($update_data), '添加权限信息');
            }
            // 提交事务
            Db::commit();
            return $this->jsonSuccessData("操作成功");
        } catch (Exception $e) {
            Log::record('【权限】' . $e->getMessage() . $e->getFile() . $e->getLine());
            // 回滚事务
            Db::rollback();
            return $this->jsonFailData($e->getMessage());
        }
    }

    /**
     * @OA\Get(path="/power/read",
     *   tags={"权限管理"},
     *   summary="权限详情",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="id", in="query", description="权限ID", @OA\Schema(type="int", default="1")),
     *   @OA\Response(
     *       response=200,
     *       description="The Member",
     *       @OA\JsonContent(type="object",
     *           @OA\Property(property="msg", type="string"),
     *           @OA\Property(property="code", type="integer", default="200"),
     *           @OA\Property(property="data", type="object",
     *               @OA\Property(property="id", type="integer", description="权限ID"),
     *               @OA\Property(property="title", type="string", description="节点标题"),
     *               @OA\Property(property="name", type="string", description="节点名称"),
     *               @OA\Property(property="type", type="integer", description="1权限 2子权限"),
     *               @OA\Property(property="node_icon", type="string", description="节点图标"),
     *               @OA\Property(property="routing", type="string", description="路由"),
     *               @OA\Property(property="pid", type="integer", description="父级ID"),
     *               @OA\Property(property="status", type="integer", description="权限状态 1正常2冻结"),
     *               @OA\Property(property="sort", type="integer", description="排序"),
     *               @OA\Property(property="update_time", type="string", description="更新时间"),
     *               @OA\Property(property="create_time", type="string", description="创建时间"),
     *           ),
     *       ),
     *    ),
     * )
     */
    public function read($id)
    {
        //
        $info = Db::name("power")->where('id', $id)->find();
        return $this->jsonSuccessData("操作成功", [
            'info' => $info
        ]);
    }

}
